import { history } from 'umi';
import {
  ProBreadcrumb,
  BasicLayoutProps,
  Settings as LayoutSettings,
  PageLoading,
  MenuDataItem,
} from '@ant-design/pro-layout';
import { UserOutlined, MenuOutlined } from '@ant-design/icons';
import { currentUser as queryCurrentUser } from '@/services/umi-demo/user';
import { selectMenus } from '@/services/umi-demo/menu';
import HeadRightContent from '@/components/HeadRightContent';
import Footer from '@/components/Footer';

// 运行时配置
// https://umijs.org/zh-CN/docs/runtime-config

interface IconInterface {
  [key: string]: any;
}

const loginPath = '/login';

const IconMap: IconInterface = {
  UserOutlined: <UserOutlined />,
  MenuOutlined: <MenuOutlined />,
};

const loopMenuItem = (menus: any): MenuDataItem[] =>
  menus.map((item: API.MenuDataItem) => ({
    name: item.name,
    path: item.path,
    icon: item.icon && IconMap[item.icon as string],
    routes: item.routes && loopMenuItem(item.routes),
  }));

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

export async function getInitialState(): Promise<{
  currentUser?: API.SessionUser;
  menus?: API.MenuDataItem[];
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.SessionUser | undefined>;
  fetchMenu?: () => Promise<API.MenuDataItem[] | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  const fetchMenu = async () => {
    try {
      const msg = await selectMenus({
        page: 1,
        limit: Number.MAX_SAFE_INTEGER,
        parentId: '-',
      });
      return msg?.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    const menus = await fetchMenu();
    return {
      fetchUserInfo,
      fetchMenu,
      currentUser,
      menus,
    };
  }

  return {
    fetchUserInfo,
    fetchMenu,
  };
}

export const layout = ({
  initialState,
}: {
  initialState: {
    settings?: LayoutSettings;
    currentUser?: API.SessionUser;
    menus?: API.MenuDataItem[];
  };
}): BasicLayoutProps => {
  return {
    rightContentRender: () => <HeadRightContent />,
    disableContentMargin: false,
    // 将面包屑显示在顶部
    headerContentRender: () => {
      return <ProBreadcrumb />;
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
        return;
      }
    },
    menu: {
      request: async () => loopMenuItem(initialState.menus),
    },
    menuHeaderRender: undefined,
    ...initialState?.settings,
  };
};
